package zju.ccnt.exception;

import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
import sun.jvm.hotspot.utilities.Assert;

import javax.validation.ConstraintViolation;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * Created by zha on 14/11/6.
 */
@ResponseStatus(value = HttpStatus.BAD_REQUEST, reason = "Request input not valid")
public class ValidationException extends BaseWebApplicationException {

    private Map<String, String> additionalInformation = null;

    public Map<String, String> getAdditionalInformation() {
        return additionalInformation;
    }

    public ValidationException(Set<? extends ConstraintViolation<?>> violations){
        super(HttpStatus.BAD_REQUEST,"Request input not valid, violations accrued.");

        Assert.that(!(violations.isEmpty()), "violations should not be empty here");
        additionalInformation= new HashMap<String, String>();
        //add the violation info
        for(ConstraintViolation<?> constraintViolation : violations) {
            additionalInformation.put(
                    constraintViolation.getPropertyPath().toString(),
                    constraintViolation.getMessage() + (constraintViolation.getInvalidValue() != null ? constraintViolation.getInvalidValue().toString() : "")
            );
        }
    }

    public String getSummary() {

        StringBuilder builder = new StringBuilder();

        String delim = "";

        int error = this.getStatus();
        builder.append(delim).append("error=\"").append(error).append("\"");
        delim = ", ";

        Map<String, String> additionalParams = this.getAdditionalInformation();
        if (additionalParams != null) {
            for (Map.Entry<String, String> param : additionalParams.entrySet()) {
                builder.append(delim).append(param.getKey()).append("=\"").append(param.getValue()).append("\"");
                delim = ", ";
            }
        }

        return builder.toString();

    }

    @Override
    public String getMessage() {
        return getSummary();
    }
}
